package com.bbgwap.utils;

import com.bbgkh.utils.*;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * Created by lixiang01 on 2/22/2017.
 */
public class HttpUtils {
    protected static  com.bbgkh.utils.BBLogger logger = com.bbgkh.utils.BBLogger.getLogger(HttpUtils.class.getName());
    /**
     * 获取所有的网页信息以String返回
     * @param entity 返回HttpEntity对象
     * @return
     */
    public static String entityToStr(HttpEntity entity) {
        StringBuffer buffer = new StringBuffer();
        try {
            if (entity != null) {

                // 获得响应字符集编码
                ContentType contentType = ContentType.getOrDefault(entity);
                Charset charset = contentType.getCharset();
                if(charset == null){
                    charset = Consts.UTF_8;
                }

                //读取返回内容
                InputStream is = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));
//				int i=0;
                String line = null;
                while ((line = br.readLine()) != null) {
                    buffer.append(new String(line.getBytes()));
//					i++;
                }
                is.close();
//				if(i>=2){
//					logger.info("+++++++进来了:");
//				}
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("解析HttpEntity出错",e);
        }
        return buffer.toString();
    }
}
